//主题树组件
import { defineComponent, onMounted, reactive, ref, watch } from 'vue';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus/lib/index';
import ModelButtonRole from '@/components/modelButtonRole';
import './index.scss';
import API from '@/services';

const ThemeTree = defineComponent({
  name: 'ThemeTree',
  props: {
    ...ElTree.props,
    isEdit: {
      type: Boolean,
      default: false
    },
    //显示状态
    reviewStatusList: {
      type: Array,
      default: () => []
    },
    /* 标题 */
    titles: {
      type: String,
      default: '标题'
    },
    /* key */
    groupKey: {
      type: Number,
      default: 1
    }
  },
  emits: ['getTreeNode'],
  setup: (props, { slots, attrs, emit }) => {
    // 获取api
    const {
      subject: {
        getSubjectsList,
        postSubjects,
        deleteSubjectsById,
        putSubjectsById
      }
    } = API;

    // tree  ref
    const tree: any = ref();
    // 当前选中节点
    const nodeInfo: any = ref({});
    // treeList
    const treeList: any = ref([]);
    // 重命名，新建 名称暂存
    const newOrEditName: any = ref('');
    // 缓存id
    const saveEditId: any = ref();
    // input ref
    const inputRef: any = ref();

    const toggle = ref({ index: -1 });

    /* 当前点击的分组id */
    const activeGroupId = ref();

    const handleName = ref();

    // 点击节点展示信息
    const nodeClickToInfo = (node: any) => {
      if (saveEditId.value) {
        tree.value.getNode(saveEditId.value);
      }
      nodeInfo.value = node;
      emit('getTreeNode', node);
    };

    // 获取树list
    const getTreeNodeList = async () => {
      try {
        const { code, data } = await getSubjectsList({
          reviewStatusList: props.reviewStatusList
        });
        if (code === 200 && data) {
          const arr = [];
          arr.push(data);
          treeList.value = arr;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /******** 右侧菜单 操作********* */
    // 点击右侧菜单项
    const subjectClick = (node: any, data: any, type: string) => {
      // 重命名
      switch (type) {
        case 'reName':
          reNameEdit(data);
          return;
        case 'remove':
          showDelModal(data.id);
          return;
        case 'addUp':
          addUpSubject(data);
          return;
        case 'addNext':
          addNextSubject(data);
          return;
        case 'addSon':
          addSonSubject(data);
          return;
        default:
          return;
      }
    };
    // 名称框失去焦点
    const nameInputOnBlur = (data: any) => {
      newOrEditName.value = '';
      if (data.id != 'new') {
        data.reName = false;
      } else {
        tree.value.remove(data);
      }
    };
    // 重命名操作
    const reNameEdit = (data: any) => {
      // 缓存名称和id
      newOrEditName.value = data.subjectName;
      saveEditId.value = data.id;
      //启动编辑状态
      data.reName = true;
      setTimeout(() => {
        inputRef.value.focus();
      }, 500);
    };

    // 新建主题（input框回车）
    const creatSubject = (e: any, data: any) => {
      if (e.keyCode === 13) {
        if (newOrEditName.value === '') {
          ElMessage.error('名称不能为空！');
        } else {
          if (data?.id === 'new' && data) {
            let subjectLevel = data.subjectLevel;
            //添加子主题
            if (handleName.value == 'addSon') {
              subjectLevel = subjectLevel + 1;
            }
            // 在上，下，子添加主题
            const newNode = {
              subjectName: newOrEditName.value,
              parentId: data.parentId,
              previousId: data.previousId,
              subjectLevel: subjectLevel
            };
            creatNewSubject(newNode);
          } else if (data?.id !== 'new' && data) {
            // 重命名
            const newNode = { subjectName: newOrEditName.value, id: data.id };
            reNameSubject(newNode);
          } else {
            // 新建一级主题，非右侧菜单
            let previousId = -1;
            if (treeList.value.length > 0) {
              previousId = treeList.value[treeList.value.length - 1].id;
            }
            creatNewSubject({
              parentId: -1,
              previousId,
              subjectLevel: 1,
              subjectName: newOrEditName.value
            });
          }
        }
      }
    };
    // 在上添加主题
    const addUpSubject = (data: any) => {
      const newNode = {
        id: 'new',
        parentId: data.parentId,
        previousId: data.previousId,
        subjectLevel: data.subjectLevel
      };
      tree.value.insertBefore(newNode, data);
      setTimeout(() => {
        inputRef.value.focus();
      }, 500);
    };
    // 在下添加主题
    const addNextSubject = (data: any) => {
      const newNode = {
        id: 'new',
        parentId: data.parentId,
        previousId: data.id,
        subjectLevel: data.subjectLevel
      };
      tree.value.insertAfter(newNode, data);
      setTimeout(() => {
        inputRef.value.focus();
      }, 500);
    };
    // 添加子主题
    const addSonSubject = (data: any) => {
      let previousId = -1;
      if (data.children && data.children.length > 0) {
        previousId = data.children[data.children.length - 1].id;
      }
      const newNode = {
        id: 'new',
        parentId: data.id,
        previousId,
        subjectLevel: data.subjectLevel
      };
      data.children.push(newNode);
      tree.value.getNode(data.id).expanded = true;
      setTimeout(() => {
        inputRef.value.focus();
      }, 500);
    };

    // 执行添加操作
    const creatNewSubject = async (params: any) => {
      try {
        const { code, data } = await postSubjects(params);
        if (code === 200) {
          getTreeNodeList();
          newOrEditName.value = '';
          ElMessage.success('创建成功');
        }
      } catch (error) {
        ElMessage.error('创建失败');
      }
    };

    // 执行重命名
    const reNameSubject = async (params: any) => {
      try {
        const { code, data } = await putSubjectsById(params);
        if (code === 200) {
          getTreeNodeList();
          newOrEditName.value = '';
          ElMessage.success('更新成功');
        } else {
          ElMessage.error('更新失败');
        }
      } catch (error) {
        ElMessage.error('更新失败');
      }
    };

    // 删除
    const showDelModal = async (id: number) => {
      saveEditId.value = id;

      ElMessageBox.alert('', '是否确认删除该主题?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      })
        .then(async () => {
          try {
            const { code, data, msg } = await deleteSubjectsById({ id });
            if (code === 200) {
              getTreeNodeList();
              saveEditId.value = null;
              ElMessage.success('删除成功');
            } else {
              ElMessage.error(msg);
            }
          } catch (error) {
            console.log(error);
            ElMessage.error('删除失败');
          }
        })
        .catch(() => {
          ElMessage.info('取消删除');
        });
    };
    // 页面加载后初始化
    onMounted(() => {
      getTreeNodeList();
    });

    watch(
      () => props?.groupKey,
      () => {
        getTreeNodeList();
      }
    );

    return () => {
      const { ...restProps } = props;
      return (
        <div class="group-container">
          <div class="group-title">{props.titles}</div>
          {/* {props.isEdit && treeList.value.length === 0 && (
            <el-input
              size="large"
              v-model={newOrEditName.value}
              onKeyup={creatSubject}
              style={{ width: '100%' }}
              placeholder="新建主题，请输入名称"
            ></el-input>
          )} */}
          <el-tree
            {...restProps}
            data={treeList.value}
            default-expanded-keys={[activeGroupId.value || 1]}
            ref={tree}
            node-key="id"
            onNodeClick={(node: any) => {
              nodeClickToInfo(node);
            }}
            expand-on-click-node={false}
            onNode-expand={(item: any) => {
              activeGroupId.value = item.id;
            }}
            v-slots={{
              default: ({ node, data }: any) => (
                <>
                  {(data.reName || data.id === 'new') && (
                    <el-input
                      size="large"
                      v-model={newOrEditName.value}
                      style={{ width: '200px' }}
                      ref={inputRef}
                      onKeyup={(e: any) => {
                        creatSubject(e, data);
                      }}
                      onBlur={() => {
                        nameInputOnBlur(data);
                      }}
                      placeholder="请输入"
                    ></el-input>
                  )}
                  {!data.reName && data.id !== 'new' && (
                    <>
                      <span
                        onMouseenter={() => (toggle.value.index = data?.id)}
                        onMouseleave={() => (toggle.value.index = -1)}
                        class="custom-tree-node"
                      >
                        <div class="custom-tree-node-item">
                          <span class="node-name">
                            {`${data.subjectName}(${data.metricNum})`}
                          </span>
                        </div>
                        {props.isEdit && (
                          <el-dropdown
                            trigger="click"
                            onCommand={(command: string) => {
                              handleName.value = command;
                              subjectClick(node, data, command);
                            }}
                            v-slots={{
                              dropdown: () => (
                                <>
                                  <el-dropdown-menu class="theme-dropdown">
                                    {data.id === 1 ? (
                                      <el-dropdown-item command="addSon">
                                        添加子主题
                                      </el-dropdown-item>
                                    ) : (
                                      <>
                                        <el-dropdown-item command="reName">
                                          重命名
                                        </el-dropdown-item>
                                        <el-dropdown-item command="addUp">
                                          上方添加主题
                                        </el-dropdown-item>
                                        <el-dropdown-item command="addNext">
                                          下方添加主题
                                        </el-dropdown-item>
                                        {data && data.subjectLevel < 3 && (
                                          <el-dropdown-item command="addSon">
                                            添加子主题
                                          </el-dropdown-item>
                                        )}
                                        {(!data.children ||
                                          data.children?.length === 0) && (
                                          <el-dropdown-item command="remove">
                                            删除
                                          </el-dropdown-item>
                                        )}
                                      </>
                                    )}
                                  </el-dropdown-menu>
                                </>
                              )
                            }}
                          >
                            {toggle.value.index === data?.id ? (
                              <span class="el-dropdown-link">· · ·</span>
                            ) : undefined}
                          </el-dropdown>
                        )}
                      </span>
                    </>
                  )}
                </>
              )
            }}
          ></el-tree>
        </div>
      );
    };
  }
});

export default ThemeTree;
